sugarfreeServices.factory('WebsocketService',
	['$websocket', '$location', '$timeout', '$http','$filter',
    function($websocket, $location, $timeout, $http,$filter){

		var status_booked = 1;
		var status_cancelled = 1 << 1;
		var status_verified = 1 << 2;


        var receipts = {
			bookingMsg : "",
			booked : [],
			verified : []
		} ;
		
		var income = {today:0, total:0};

        console.log("new socket");
		var url = "ws://" + $location.host() + ":" + $location.port() + "/gym/websocket";
        console.info('#url#',url);
        var ws = $websocket(url);
        var connected_successfully = false;
        ws.onOpen(function(){
        	console.log("connected");
        	connected_successfully = true;
        	
        }) ;
        ws.onClose(function(event){
        	console.log("closed");
        	if(true === connected_successfully){
	        	ws = $websocket(url);
        	}
        });
        
        ws.onError(function(event){
        	console.log("error:" + event);
        	connected_successfully = false;
        });
        
        ws.onMessage(function(event){

			var receipt;
            console.log("new message");

			try{
				receipt = JSON.parse(event.data) ;
			} catch(e){
				console.log(e);
			}

			console.log(receipt.status);
			if(status_booked === receipt.status){
                console.log("booked");
                receipts.booked.push(receipt);
                receipts.bookingMsg = receipt.member.mobile +
                     "预约了" +  
                     $filter('date')($filter('dateParse')(receipt.lesson.beginTime),"yyyy-MM-dd HH:mm") +
                     receipt.lesson.course.classType.name +
                     receipt.lesson.course.title;
			} else if(status_verified === receipt.status){
                console.log("verify");
                receipts.verified.unshift(receipt);
              	if(receipts.verified.length>10){
                	receipts.verified.pop();
                }
				income.today += receipt.paidInBean;
				income.total += receipt.paidInBean;
				console.log(income);
				console.info("receipt~~",receipt);
			}

			console.log(receipt);

			$timeout(1);
        }

        );
        return {

			receipts : receipts,

        	getIncome : function(){
        		return income;
        	},

        	setIncome:function(value){
        		income = value;
        	}
        };

    }]
);
